package com.swak.codec;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

import com.swak.exception.CacheException;

/**
 * 封装各种格式的编码解码工具类. 1.Commons-Codec的 hex/base64 编码 2.自制的base62 编码
 * 3.Commons-Lang的xml/html escape 4.JDK提供的URLEncoder
 *
 * @author: lifeng
 * @date: 2020/3/29 10:46
 */
public class Encodes {

	public static String encodeHex(byte[] input) {
		return Hex.encodeHexString(input);
	}

	public static byte[] decodeHex(String input) {
		return Hex.decodeHex(input.toCharArray());
	}

	public static String encodeBase64(byte[] input) {
		return Base64.encodeBase64String(input);
	}

	public static String encodeBase64UrlSafeString(byte[] input) {
		return Base64.encodeBase64URLSafeString(input);
	}

	public static byte[] decodeBase64(String input) {
		return Base64.decodeBase64(input);
	}

	public static String decodeBase64(String input, String charsetName) {
		try {
			return new String(Base64.decodeBase64(input), charsetName);
		} catch (UnsupportedEncodingException e) {
			return null;
		}
	}

	/**
	 * bug: 原生的会将 空格转为 +； 导致 js 来认为是 + ;
	 * 
	 * @param part
	 * @return
	 */
	public static String urlEncode(String part) {
		try {
			String encoded = URLEncoder.encode(part, StandardCharsets.UTF_8.toString());
			return encoded.replaceAll("\\+", "%20");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	public static String urlDecode(String part) {

		try {
			return URLDecoder.decode(part, StandardCharsets.UTF_8.toString());
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	public static String toUnicode(String input) {
		StringBuilder builder = new StringBuilder();
		char[] chars = input.toCharArray();
		for (char ch : chars) {
			if (ch < 256) {
				builder.append(ch);
			} else {
				builder.append("\\u").append(Integer.toHexString(ch & 0xffff));
			}
		}
		return builder.toString();
	}

	public static byte[][] encodeMany(final String... strs) {
		byte[][] many = new byte[strs.length][];
		for (int i = 0; i < strs.length; i++) {
			many[i] = encode(strs[i]);
		}
		return many;
	}

	public static byte[] encode(final String str) {
		if (str == null) {
			throw new CacheException("value cannot be null");
		}
		return str.getBytes(StandardCharsets.UTF_8);
	}

	public static String encode(final byte[] data) {
		return data != null ? new String(data, StandardCharsets.UTF_8) : null;
	}
}
